package com.wzdigit.wms.wms.service.core.transfer;

import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.inventory.Goods;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.TransferDtl;
import com.wzdigit.wms.basic.domain.transfer.TransferDtlGoods;
import com.wzdigit.wms.basic.domain.transfer.TransferHeader;
import com.wzdigit.wms.basic.enums.TransferTypeEnum;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.wms.client.web.service.common.wms2sap.ZDT_Reserve;
import com.wzdigit.wms.wms.client.web.service.wms2sap.transfer.ZDT_007_ReqRecordsHead;
import com.wzdigit.wms.wms.client.web.service.wms2sap.transfer.ZDT_007_ReqRecordsHeadItems;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.wms.service.basic.SkuService;
import com.wzdigit.wms.wms.service.basic.WarehouseService;
import com.wzdigit.wms.wms.service.core.GoodsService;
import com.wzdigit.wms.wms.service.mapping.CodeMappingNewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 调拨单 服务类
 * </p>
 *
 * @author
 * @since 2021-01-19
 */
@Service
@Slf4j
public class TransferCodeService {

    @Autowired
    @Lazy
    private WarehouseService warehouseService;
    
    @Autowired
    private TransferDtlService transferDtlService;

    @Autowired
    private TransferDtlGoodsService transferDtlGoodsService;

	@Autowired
	private GoodsService goodsService;
	
	@Autowired
    private SkuService skuService;
	
	@Autowired
    private CodeMappingNewService codeMappingNewService;
	
    /**
     * 关单后写进来
     *
     * @param loginName
     * @param transferHeader
     * @param transferType
     */
    public IfPostback ainsertIfpostbackList(String loginName, TransferHeader transferHeader, String transferType) {
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_TRANSFER.getEnumName());
        ifPostback.setPostbackNo(transferHeader.getTransferNo());
        ifPostback.setPostbackType(transferType);
        ifPostback.setPostbackSourceNo(transferHeader.getSourceNo());


        List<TransferDtl> transferDtlList = transferDtlService.getByHeaderId(transferHeader.getTransferHeaderId());

        Integer fmWhs = transferHeader.getFmWhs();//单头源仓库
        Integer toWhs = transferHeader.getToWhs();//单头目的仓

        ZDT_007_ReqRecordsHead head = new ZDT_007_ReqRecordsHead();

        if (transferType.equals(TransferTypeEnum.T03.getCode())) {
            //组织间调拨
            head.setZCJLX("2");//创建类型
            head.setBWART("");//移动类型（创建类型2无需填）

        } else if (transferType.equals(TransferTypeEnum.T04.getCode())) {
            //销售订单调拨
            head.setZCJLX("4");//创建类型

            String erpMoveType = transferHeader.getErpMoveType();
            if (erpMoveType == null) {
                erpMoveType = "";
                log.warn("ERP_MOVE_TYPE字段的值为NULL");
            }
            head.setBWART(erpMoveType);//移动类型（创建类型2无需填）

        } else if (transferType.equals(TransferTypeEnum.T05.getCode()) || transferType.equals(TransferTypeEnum.T06.getCode())) {
            //借机||还机
            head.setZCJLX("1");//创建类型
            head.setBWART("311");//移动类型（创建类型2 无需填）
        }

        head.setZGLJYD(transferHeader.getTransferNo());//调拨单号

        if (transferHeader.getPurchsingOrg() != null) {
            head.setEKORG(transferHeader.getPurchsingOrg());//采购组织（创建类型2必填）
        } else {
            head.setEKORG("");//采购组织（创建类型2必填）
        }

        if (transferHeader.getCompanyCode() != null) {
            head.setBUKRS(transferHeader.getCompanyCode());//公司代码（创建类型2必填）
        } else {
            head.setBUKRS("");//公司代码（创建类型2必填）
        }


        head.setZCJR(loginName);//创建人
        head.setZCJRZH(loginName);//创建人账号

        head.setZCJRQ(getDateStr());//创建日期
        head.setZCJSJ(getTimeStr());//创建时间


        ZDT_Reserve reserve = new ZDT_Reserve();

        reserve.setRsv1("");
        reserve.setRsv2("");
        reserve.setRsv3("");
        reserve.setRsv4("");
        reserve.setRsv5("");
        head.setRSV(reserve);


        List<ZDT_007_ReqRecordsHeadItems> items = new ArrayList<>();

        //设置ITEMS
        for (TransferDtl transferDtl : transferDtlList) {
            String fmFactory = transferDtl.getFmFactory();
            Integer fmQaStatus = transferDtl.getFmQaStatus();
            Warehouse fmWarehouse = warehouseService.selectByPK(fmWhs);
            //根据WMS的仓库CODE+factory找SAP的仓库CODE
            String fmWhsCode = fmWarehouse.getWhsCode();
            CodeMapping fmCodeMapping = codeMappingNewService.selectByWhsCodeAndFactory(fmFactory, fmWhsCode, fmQaStatus);
            if (fmCodeMapping == null) {
                String message = String.format("根据调拨单明细的仓库CODE:【%s】和工厂代码:【%s】未找SAP对应的仓库信息,请维护【内外部系统代码映射表】", fmWhsCode, fmFactory);
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }


            String toFactory = transferDtl.getToFactory();
            Integer toQaStatus = transferDtl.getToQaStatus();
            Warehouse toWarehouse = warehouseService.selectByPK(toWhs);
            //根据WMS的仓库CODE+factory找SAP的仓库CODE
            String toWhsCode = toWarehouse.getWhsCode();
            CodeMapping toCodeMapping = codeMappingNewService.selectByWhsCodeAndFactory(toFactory, toWhsCode, toQaStatus);
            if (toCodeMapping == null) {
                String message = String.format("根据调拨单明细的仓库CODE:【%s】和工厂代码:【%s】未找SAP对应的仓库信息,请维护【内外部系统代码映射表】", toWhsCode, toFactory);
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }


//            if (transferDtl.getFmVendor() != null) {
            log.info("供应商：{}", transferDtl.getUdf5());
            log.info("供应商：{}", transferDtl.getUdf5());
            log.info("供应商：{}", transferDtl.getUdf5());
            if (transferDtl.getUdf5() != null) {
//                head.setLIFNR(transferDtl.getFmVendor().toString());//供应商 （创建类型2必填），YC说明细的FM供应商都是一样的
                head.setLIFNR(transferDtl.getUdf5());//供应商 （创建类型2必填），YC说明细的FM供应商都是一样的,YC说改成取这个值
            } else {
                head.setLIFNR("");//供应商 （创建类型2必填）
            }

            List<TransferDtlGoods> transferDtlGoods = transferDtlGoodsService.selectByDtlId(transferDtl.getTransferDtlId());

            BigDecimal qty = transferDtlGoods.stream().filter(s -> s.getQty() != null).map(s -> s.getQty()).reduce(BigDecimal.ZERO, BigDecimal::add);

            TransferDtlGoods dtlGoods = transferDtlGoods.get(0);
            Goods goods = goodsService.selectBySn(dtlGoods.getGoodsSn());


            ZDT_007_ReqRecordsHeadItems headItems = new ZDT_007_ReqRecordsHeadItems();

            headItems.setZCGHH(transferDtl.getTransferLineNo());//调拨单行号

            //特殊库存 的意思 就是库存是绑定订单的,转出转入都绑定,所以是两个e from SAP——WZP
            headItems.setSOBKZ("E");//特殊库存标识（转出）
            headItems.setUMSOK("E");//特殊库存标识（转入）


            headItems.setKDAUF(transferDtl.getFmSoNo());//订单号码（转出）
            headItems.setKDPOS(transferDtl.getFmSoLineNo());//订单行项目（转出）

            headItems.setMAT_KDAUF(transferDtl.getToSoNo());//订单号码（转入）
            headItems.setMAT_KDPOS(transferDtl.getToSoLineNo());//订单行项目（转入）

            headItems.setWERKS(fmFactory);//工厂（转出）
            headItems.setUMLGO(fmCodeMapping.getMappingCode());//库位（转出）/SAP说传他们的仓库


            headItems.setUMWRK(toFactory);//工厂（转入）
            headItems.setLGORT(toCodeMapping.getMappingCode());//库位（转入）/SAP说传他们的仓库

            Sku sku = skuService.getSkuByPk(goods.getSkuId());
            headItems.setMATNR(sku.getSkuCode());//物料号

//            headItems.setMENGE(goods.getQty().toString());//数量
            headItems.setMENGE(qty.toString());//数量

            headItems.setBUDAT(getDateStr());//过帐日期

            ZDT_Reserve zdt_reserve = new ZDT_Reserve();
            zdt_reserve.setRsv1("");
            zdt_reserve.setRsv2("");
            zdt_reserve.setRsv3("");
            zdt_reserve.setRsv4("");
            zdt_reserve.setRsv5("");

            headItems.setRSV(zdt_reserve);

            items.add(headItems);
        }

        ZDT_007_ReqRecordsHeadItems[] recordsHeadItemsArr = items.toArray(new ZDT_007_ReqRecordsHeadItems[items.size()]);

        head.setItems(recordsHeadItemsArr);

        List<ZDT_007_ReqRecordsHead> headArrays = new ArrayList<ZDT_007_ReqRecordsHead>();
        headArrays.add(head);

        String jsonString = JSON.toJSONString(headArrays);


        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setCreateUser(loginName);
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());

        return ifPostback;
    }
    
    /**
     * 格式化日期，8位
     * 
     * @return
     */
    public String getDateStr() {
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateStr = formatter.format(now);
        return dateStr;
    }


    /**
     * 获得当前时间时分秒
     *
     * @return
     */
    private String getTimeStr() {
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        String timeStr = formatter.format(now);
        return timeStr;
    }
}
